package org.fastsyncer.web.controller.index;

import org.fastsyncer.biz.ConnectorService;
import org.fastsyncer.common.entity.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/connector")
public class ConnectorController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ConnectorService connectorService;

    @GetMapping("/page/{page}")
    public String page(HttpServletRequest request, @PathVariable("page") String page, String id) {
        return "connector/" + page;
    }

    @RequestMapping(value = "/alive")
    @ResponseBody
    public RestResult alive(HttpServletRequest request, @RequestParam(value = "json") String json) {
        try {
            return RestResult.restSuccess(connectorService.alive(json));
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getMessage());
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public RestResult save(HttpServletRequest request, @RequestParam(value = "json") String json) {
        try {
            return RestResult.restSuccess(connectorService.save(json));
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getMessage());
        }
    }

    @PostMapping("/remove")
    @ResponseBody
    public RestResult remove(HttpServletRequest request, @RequestParam(value = "id") String id) {
        try {
            return RestResult.restSuccess(connectorService.remove(id));
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getMessage());
        }
    }

    @GetMapping("/getAll")
    @ResponseBody
    public RestResult getAll(HttpServletRequest request) {
        try {
            return RestResult.restSuccess(connectorService.getConnectorAll());
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getMessage());
        }
    }

}
